const express = require('express')
const cors = require('cors')
const Joi = require('joi')
const config = require('./config')
var { expressjwt } = require("express-jwt");
const app = express()

const userRouter = require('./router/user')
const infoRouter = require('./router/userinfo')
const artCateRouter = require('./router/artcate')
const articleRouter = require('./router/article')


app.use(cors())
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use('/uploads/',express.static('./uploads',))

app.use((req, res, next) => {
    res.cc = (err, status = 1) => {
        res.send({
            status,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

//解析 token
app.use(expressjwt({secret:config.secret,algorithms:['HS256']}).unless({ path: [/^\/api\//] }))

app.use('/api', userRouter)
app.use('/my',infoRouter)
app.use('/my/artcate',artCateRouter)
app.use('/my/article',articleRouter)

//错误中间件
app.use(function (err, req, res, next) {
    // Joi 参数校验失败
    if (err instanceof Joi.ValidationError) {
        return res.cc(err)
    }
    if (err.name === "UnauthorizedError") {
        return res.status(401).cc("身份认证失败！");
    } 
    // 未知错误
    res.cc(err)
})

app.listen(3000)